package com.salon.client.tabItems;

import java.util.ArrayList;
import java.util.List;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.data.BasePagingLoader;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.BeanModelFactory;
import com.extjs.gxt.ui.client.data.BeanModelLookup;
import com.extjs.gxt.ui.client.data.BeanModelReader;
import com.extjs.gxt.ui.client.data.LoadEvent;
import com.extjs.gxt.ui.client.data.PagingLoadConfig;
import com.extjs.gxt.ui.client.data.RpcProxy;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnData;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer;
import com.extjs.gxt.ui.client.widget.grid.GridSelectionModel;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.RowData;
import com.extjs.gxt.ui.client.widget.layout.RowLayout;
import com.extjs.gxt.ui.client.widget.menu.SeparatorMenuItem;
import com.extjs.gxt.ui.client.widget.toolbar.PagingToolBar;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.PopupPanel;
import com.salon.client.GreetingServiceAsync;
import com.salon.client.Salon;
import com.salon.client.beans.IncomeBean;
import com.salon.client.beans.IncomeMaterialsBean;
import com.salon.client.beans.MaterialBean;
import com.salon.client.beans.ParentPagingLoadResult;
import com.salon.client.beans.PriceBean;
import com.salon.client.beans.WhereBean;
import com.salon.client.widgets.IncomeDialog;
import com.salon.client.widgets.IncomeMaterialDialog;
import com.salon.client.widgets.PriceDialog;
import com.salon.client.widgets.UsedMaterialDialog;
import com.salon.client.widgets.panels.IncomeMaterialsPanel;
import com.salon.client.widgets.panels.UsedMaterialsPanel;

public class PriceTabItemPanel extends ContentPanel{
	private ContentPanel pricePanel = new ContentPanel();
	private ContentPanel priceMaterPanel = new ContentPanel();
	
	
	protected ListStore<BeanModel> store = null;
	protected ListStore<BeanModel> matStore = new ListStore<BeanModel>();
	protected BasePagingLoader<ParentPagingLoadResult<PriceBean>> loader = null;
	protected PagingToolBar toolbar = new PagingToolBar(20);
	protected Grid<BeanModel> grid;
	protected Grid<BeanModel> matGrid;
	public PriceBean selectedBean = null;
	//public List<WhereBean> wheres = new ArrayList<WhereBean>();
	private static BeanModelFactory materialFactory = null;
	
	private List<WhereBean> wheres = null;
	
	static {
		try {
			materialFactory = BeanModelLookup.get().getFactory(IncomeMaterialsBean.class);
		}
		catch (Exception e) {}
	}
	
	public PriceTabItemPanel() {
		setBodyBorder(false);
		setHeaderVisible(false);
		setButtonAlign(HorizontalAlignment.CENTER);
		
		RowLayout r = new RowLayout();
		r.setOrientation(Style.Orientation.HORIZONTAL);
		setLayout(r);
		
		pricePanel.setBodyBorder(false);
		pricePanel.setHeading("Услуги");
		pricePanel.setLayout(new FitLayout());
		
		priceMaterPanel.setBodyBorder(false);
		priceMaterPanel.setHeading("Калькуляция");
		priceMaterPanel.setLayout(new FitLayout());
		
		toolbar.setBorders(true);
		setBottomComponent(toolbar);
		
		initComponents();
		
	}
	
	protected void initComponents() {
		addButton("Добавить услугу", "brit-add-user", new SelectionListener<ButtonEvent>() {
			
			public void componentSelected(ButtonEvent ce) {
				PriceDialog dlg = new PriceDialog(PriceTabItemPanel.this);
				dlg.show();
			}
			
		});
		
		addButton("Добавить расходник", "brit-add-user", new SelectionListener<ButtonEvent>() {
			
			public void componentSelected(ButtonEvent ce) {
				if (selectedBean == null) {
					Info.display("Выберите ", "услугу");
					return;
				}
				//UsedMaterialDialog dlg = new UsedMaterialDialog(PriceTabItemPanel.this, selectedBean.getId());
				//dlg.show();
				PopupPanel dlg = new PopupPanel();
				dlg.setAnimationEnabled(true);
				dlg.setSize("500px", "300px");
				UsedMaterialsPanel panel = new UsedMaterialsPanel(PriceTabItemPanel.this, dlg, selectedBean.getId());
				dlg.add(panel);
				dlg.center();
			}
			
		});
		
		addButton("Удалить услугу", "brit-delete-user", new SelectionListener<ButtonEvent>() {
			
			public void componentSelected(ButtonEvent ce) {
				if (selectedBean != null) {
					((GreetingServiceAsync) Registry.get(Salon.SERVICE))
					.deleteItem("price", selectedBean.getId(), 
							new AsyncCallback<Void>() {

								@Override
								public void onFailure(Throwable caught) {
									Info.display("Не удалось", "удалить услугу");
									
								}

								@Override
								public void onSuccess(Void result) {
									Info.display("Удаление услугу", "успешно");
									PriceTabItemPanel.this.refreshStore();
									
								}
						
					});
				}
			}
		});
		
		addButton("Удалить товар", "brit-delete-user", new SelectionListener<ButtonEvent>() {
			
			public void componentSelected(ButtonEvent ce) {
				IncomeMaterialsBean bean = null;
				if (matGrid.getSelectionModel() != null) {
					if (matGrid.getSelectionModel().getSelectedItem() != null) {
						bean = matGrid.getSelectionModel().getSelectedItem().getBean();
					}
				}
				if (bean != null) {
					((GreetingServiceAsync) Registry.get(Salon.SERVICE))
					.deleteItem("price_details", bean.getId(), 
							new AsyncCallback<Void>() {

								@Override
								public void onFailure(Throwable caught) {
									Info.display("Не удалось", "удалить товар");
									
								}

								@Override
								public void onSuccess(Void result) {
									Info.display("Удаление товара", "успешно");
									PriceTabItemPanel.this.refreshStore();
									
								}
						
					});
				}
			}
		});
		RpcProxy<ParentPagingLoadResult<PriceBean>> proxy = getProxy();
		
		BeanModelReader reader = new BeanModelReader();
		// loader and store
		loader = new BasePagingLoader<ParentPagingLoadResult<PriceBean>>(proxy,
				reader);
		store = new ListStore<BeanModel>(loader) {
			protected void onLoadException(LoadEvent le) {
				Info.display("Load Error", "Error message was: {0}",
						le.exception.getMessage());
			}
			@Override
			protected void onLoad(LoadEvent le) {
				super.onLoad(le);
			}
		};
		
		toolbar.bind(loader);
		refreshStore();
		
		grid = new Grid<BeanModel>(store, getColomnModel());
		grid.setStyleAttribute("borderTop", "none");
		grid.setBorders(true);
		grid.setLoadMask(true);
		grid.getView().setForceFit(true);
		GridSelectionModel<BeanModel> sel = grid.getSelectionModel();
		sel.setSelectionMode(Style.SelectionMode.SINGLE);
		
		sel.addListener(Events.SelectionChange,
				new Listener<SelectionChangedEvent<BeanModel>>() {
					public void handleEvent(
							final SelectionChangedEvent<BeanModel> selEv) {
						if (selEv.getSelectedItem() != null) {
							setSelected((PriceBean)selEv.getSelectedItem().getBean());
						}
					}
				});
		pricePanel.add(grid);
		add(pricePanel, new RowData(.3, 1));
		
		initMaterialPanel();
	}
	
	private void initMaterialPanel() {
		matGrid = new Grid<BeanModel>(matStore, getMaterialColomnModel());
		matGrid.setStyleAttribute("borderTop", "none");
		matGrid.setBorders(true);
		matGrid.setLoadMask(true);
		matGrid.getView().setForceFit(true);
		GridSelectionModel<BeanModel> sel = matGrid.getSelectionModel();
		sel.setSelectionMode(Style.SelectionMode.SINGLE);
		
		sel.addListener(Events.SelectionChange,
				new Listener<SelectionChangedEvent<BeanModel>>() {
					public void handleEvent(
							final SelectionChangedEvent<BeanModel> selEv) {
						/*if (selEv.getSelectedItem() != null) {
							setSelected((IncomeBean)selEv.getSelectedItem().getBean());
						}*/
					}
				});
		priceMaterPanel.add(matGrid);
		add(priceMaterPanel, new RowData(.7, 1));
	}
	
	private void setSelected(PriceBean bean) {
		if (bean != null) {
			selectedBean = bean;
			
			matStore.removeAll();
			
	        if (materialFactory != null) {
	        	for (IncomeMaterialsBean b : selectedBean.getList()) {
	        		matStore.add(materialFactory.createModel(b));
	        	}
	        }
		}
		else {
			selectedBean = null;
			matStore.removeAll();
		}
		
	}
	
	private RpcProxy<ParentPagingLoadResult<PriceBean>> getProxy() {
		RpcProxy<ParentPagingLoadResult<PriceBean>> proxy = new RpcProxy<ParentPagingLoadResult<PriceBean>>() {

			@Override
			protected void load(Object loadConfig,
					AsyncCallback<ParentPagingLoadResult<PriceBean>> callback) {
				PagingLoadConfig ploadConfig = (PagingLoadConfig) loadConfig;
				int offset = ploadConfig.getOffset();
				((GreetingServiceAsync) Registry.get(Salon.SERVICE))
						.getPrice(offset, ploadConfig.getLimit(), wheres,
								callback);
				
			}
		};
		
		return proxy;
	}
	
	private ColumnModel getColomnModel() {
		List<ColumnConfig> configs = new ArrayList<ColumnConfig>();

		ColumnConfig conf = new ColumnConfig("name", "Имя услуги", 70);
		configs.add(conf);
	
		conf = new ColumnConfig("cost", "Цена, руб", 50);
		configs.add(conf);
		
		ColumnModel cm = new ColumnModel(configs);
		return cm;
	}
	
	GridCellRenderer<BeanModel> nameRenderer = null;

	public GridCellRenderer<BeanModel> getNameRenderer() {
		if (nameRenderer == null) {
			nameRenderer = new GridCellRenderer<BeanModel>() {

				@Override
				public Object render(BeanModel model, String property,
						ColumnData config, int rowIndex, int colIndex,
						ListStore<BeanModel> store, Grid<BeanModel> grid) {
					IncomeMaterialsBean bean = model.getBean();
					if (bean != null) {
						return bean.getDisplayF();
					}
					return "";
				}
			};
		}
		return nameRenderer;
	}
	
	private ColumnModel getMaterialColomnModel() {
		List<ColumnConfig> configs = new ArrayList<ColumnConfig>();
		
		ColumnConfig conf = new ColumnConfig("name", "Наименование товара", 150);
		conf.setRenderer(getNameRenderer());
		configs.add(conf);
		
		conf = new ColumnConfig("count", "Количество", 50);
		configs.add(conf);
		
		
		ColumnModel cm = new ColumnModel(configs);
		return cm;
	}
	
	public void refreshStore(/*boolean isSearch*/) {
		if (store == null)
			return;
		store.removeAll();
		if (loader == null)
			return;
		/*if (isSearch) {
			loader.setOffset(0);
		}*/
		loader.load();
	}
	
	int row = 10;
	protected void addButton(String title, String icon, SelectionListener<ButtonEvent> listener) {
		if (row == 10) {
			toolbar.insert(new SeparatorMenuItem(), ++row);
		}
		
		Button button = new Button(title);
		button.addSelectionListener(listener);
		if (icon != null) {
			button.setIcon(IconHelper.createStyle(icon));
		}
		toolbar.insert(button, ++row);
	}
}
